package com.harmony.pilot.llm.provider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.harmony.pilot.common.dto.LLMRequest;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 华为盘古大模型提供商实现
 */
@Slf4j
@Component
public class HuaweiProvider implements LLMProvider {
    
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;
    
    @Value("${llm.huawei.api-key}")
    private String apiKey;
    
    @Value("${llm.huawei.model}")
    private String model;
    
    @Value("${llm.huawei.endpoint}")
    private String endpoint;
    
    public HuaweiProvider() {
        this.objectMapper = new ObjectMapper();
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }
    
    @Override
    public String generate(LLMRequest request) {
        log.info("Generating with Huawei Pangu");
        return callHuaweiAPI(request);
    }
    
    @Override
    public String complete(LLMRequest request) {
        log.info("Completing with Huawei Pangu");
        return callHuaweiAPI(request);
    }
    
    @Override
    public String analyze(LLMRequest request) {
        log.info("Analyzing with Huawei Pangu");
        return callHuaweiAPI(request);
    }
    
    @Override
    public String chat(LLMRequest request) {
        log.info("Chatting with Huawei Pangu");
        return callHuaweiAPI(request);
    }
    
    @Override
    public String getDefaultModel() {
        return model;
    }
    
    /**
     * 调用华为API
     * 注意：这是示例实现，实际需要根据华为盘古API文档调整
     */
    private String callHuaweiAPI(LLMRequest request) {
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", request.getModel() != null ? request.getModel() : model);
            requestBody.put("prompt", request.getPrompt());
            
            if (request.getTemperature() != null) {
                requestBody.put("temperature", request.getTemperature());
            }
            
            if (request.getMaxTokens() != null) {
                requestBody.put("max_tokens", request.getMaxTokens());
            }
            
            String jsonBody = objectMapper.writeValueAsString(requestBody);
            
            Request httpRequest = new Request.Builder()
                    .url(endpoint + "/generate")
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .post(RequestBody.create(jsonBody, MediaType.parse("application/json")))
                    .build();
            
            try (Response response = client.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    log.error("Huawei API call failed: {}", response.code());
                    return "Error: Huawei API call failed";
                }
                
                String responseBody = response.body().string();
                @SuppressWarnings("unchecked")
                Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
                return (String) responseMap.getOrDefault("text", "No response");
            }
            
        } catch (Exception e) {
            log.error("Failed to call Huawei API", e);
            return "Error: " + e.getMessage();
        }
    }
}

